import gift from '@/components/gift'
import alertBindPhone from '@/views/alert_bind_phone/index'
import {roomInitRoomChat,roomInitRoomVideo} from '@/api/room'
import {mapGetters} from 'vuex'
import ChatDisplay from '@/utils/xchat/chatDisplay'
import XMessager from '@/utils/xMessager/xMessager'
import Xchat from '@/utils/xMessager/chat/Xchat'
import XchatH5Player from '@/utils/xMessager/player/mobile/fullScreenPlayer'
import {Base64} from '@/utils/xchat/base64'
import {formatWatchServer, getParents, isIOS, isWeixin} from '@/utils'
import {MSG_LOGIN_ACK,MSG_REENTER,MSG_SESSION_PARAM,MSG_SOMEBODY_IN,MSG_SOMEBODY_OUT,MSG_ROOMHOT,MSG_SOMEBODY_CHATENABLE,MSG_KICKOUT,MSG_TOKEN_INFO,MSG_TOKEN_REQUEST,MSG_ROOM_REINIT,MSG_SOCKET_ERROR} from '@/utils/xchatMessageHandle'
import {getRoomPassword} from '@/utils/auth'
export default{
	inject:['skeletonLoad'],
	data(){
		return{
			height:undefined,
			fullScreenPlayer: null,
			xmessager:null,
			chatDisplay:null,
			chat:null,
			searchQuery:{
				room_id:this.room_id,
				eng_name:this.eng_name,
				room_password:undefined
			},
			loginDialog:false,
			loginTimer:null,
			playerLoading:false,
			watchServer:[],
			faceImgArr:[],
			faceAlt:["[微笑]", "[撇嘴]", "[色]", "[发呆]", "[得意]", "[流泪]", "[害羞]", "[闭嘴]", "[睡]", "[大哭]", "[尴尬]", "[发怒]", "[调皮]", "[呲牙]", "[惊讶]", "[难过]", "[酷]", "[冷汗]", "[抓狂]", "[吐]", "[偷笑]", "[可爱]", "[白眼]", "[傲慢]", "[饥饿]", "[困]", "[惊恐]", "[流汗]", "[憨笑]", "[大兵]", "[奋斗]", "[咒骂]", "[疑问]", "[嘘]", "[晕]", "[折磨]", "[衰]", "[骷髅]", "[敲打]", "[再见]", "[擦汗]", "[抠鼻]", "[鼓掌]", "[糗大了]", "[坏笑]", "[左哼哼]", "[右哼哼]", "[哈欠]", "[鄙视]", "[委屈]", "[快哭了]", "[阴险]", "[亲亲]", "[吓]", "[可怜]", "[菜刀]", "[西瓜]", "[啤酒]", "[篮球]", "[乒乓]", "[咖啡]", "[饭]", "[猪头]", "[玫瑰]", "[凋谢]", "[示爱]", "[爱心]", "[心碎]", "[蛋糕]", "[闪电]", "[炸弹]", "[刀]", "[握手]", "[胜利]", "[便便]", "[NO]", "[OK]", "[抱拳]", "[弱]", "[强]"],
			emojiShow:false,
			emojiLoad:true,
			openHls:false,
			giftArr: [],
			initData: null,
			giftShow: false
		}
	},
	props:{
		room_id:{
			type:String
		},
		eng_name:{
			type:String
		}
	},
	computed:{
		...mapGetters([
		  'user',
			'token',
			'roomLive',
			'micLoading',
			'micIndex',
			'roompara',
			'micLoadingTimer'
		])
	},
	components:{
		gift,
		alertBindPhone
	},
	created(){
		this.skeletonLoad()
		if("login_alert_time" in this.roompara && this.roompara.login_alert_time !== 0){
			this.loginTimer = setInterval(()=>{
				this.loginDialog = true
			},this.roompara.login_alert_time * 1000 * 60)
		}
		if(getRoomPassword(`${this.$route.params.roomid}`)){
			this.searchQuery.room_password = getRoomPassword(`${this.$route.params.roomid}`)
		}
		const initData = {
			room_id: this.room_id, 
			eng_name: this.eng_name, 
			room_password: this.searchQuery.room_password
		}
		this.initData = initData
		this.playerLoading = true
		Promise.all([roomInitRoomChat(this.searchQuery),roomInitRoomVideo(this.searchQuery)]).then(result=>{
			let wsres = result[0]
			let videores = result[1]
			this.playerLoading = false
			//聊天start
			let userpara = JSON.parse(Base64.decode(wsres.data.appdata))
			let ws_param = {
				ip : wsres.data.chat_server_ip,		//"192.168.0.120",
				// port : 19288,	//roompara.serverpo
				uid : parseInt(wsres.data.uid),
				room_id : wsres.data.room_id,
				level : wsres.data.levelinroom,
				token : wsres.data.chat_token,
				nickname : Base64.decode(userpara.nickname_b64),
				chatdisable : 0,
				appdata :Base64.encode(JSON.stringify(userpara)),
				wss: wsres.data.wss,
			}
			this.$store.commit("SET_WSPARAM",ws_param)
			videores.data.is_live = videores.data.is_live && videores.data.watch_server
			this.$store.commit('SET_ROOMLIVE',videores.data.is_live)
			this.$store.commit('SET_ROOMCHANGE',!videores.data.is_live)
			this.xmessager = new XMessager(ws_param)
			this.xmessager.appdata = JSON.parse(Base64.decode(this.xmessager.appdata))
			//聊天服务器
			new Xchat(ws_param).then(chat=>{
				this.chat = chat
				this.$store.commit('SET_WS',this.chat.websocket.ws)
				//聊天end
				this.$nextTick(()=>{
					if(videores.data.watch_server && videores.data.is_live){
						if(("login_alert_time" in this.roompara && this.roompara.login_alert_time !== 0) || this.user.logined){
							this.fullScreenPlayer = this.initPlayer(videores.data.watch_server)
							this.playerEvents()
						}
					}
					this.chatDisplay = new ChatDisplay(this.$refs.pubChatWrap,this.xmessager,this.mode,50)
					this.commonChatEvents()
					this.chatEvents()
				})
			})

		}).catch(err=>{
			this.playerLoading = false
			console.log(err)
		})
		this.faceImgArr = this.faceAlt.reduce((acc,cur,index)=>{
			acc.push(require(`@/assets/images/face/${index}.png`))
			return acc
		},this.faceImgArr)
	},
	methods:{
		initPlayer(watchServer,openHls = false,serverDecode = true,currentHlsIndex = 0,sleep = 0){
			//销毁播放器重新初始化播放器后不需要在解码
			if(serverDecode){
				watchServer = formatWatchServer(watchServer,Base64)
			}
			this.watchServer = watchServer
			let video_param = {
				el:'fullscreen-player-wrap',
				watchServer:watchServer,
				mode:this.mode,
				openHls:openHls,
				autoSeek:true,
				currentHlsIndex:currentHlsIndex,
				openWebGl: false,
				sleep
			}
			return new XchatH5Player(video_param)
		},
		destroyPlayer(){
			if(this.fullScreenPlayer){
				this.fullScreenPlayer.destroy()
			}
		},
		setPrivateChatArray(private_chat_array){
			if(this.xmessager.level < 500){
				this.giftArr = private_chat_array = private_chat_array.filter((item)=>{
					return (item.uid != this.xmessager.uid && item.level >= 500)
				})
			}else{
				this.giftArr = private_chat_array = private_chat_array.filter((item)=>{
					if(item.uid != this.xmessager.uid){
						if (item.level >= 500) {
							return true
						} else if (item.appdata.title >= 1 && item.appdata.levelinroom !== 80) {
							return true
						}
					}
				})
			}
			this.$store.commit('SET_PRIVATECHATARRAY',private_chat_array)
		},
		loginAckHandler(param){
			MSG_LOGIN_ACK(param,{xmessager:this.xmessager,chatDisplay:this.chatDisplay})
		},
		reEnterHandler(param){
			MSG_REENTER(param,{xmessager:this.xmessager,player:this.fullScreenPlayer,layer:this.$layer})
		},
		sessionParamHandler(param){
			MSG_SESSION_PARAM(param,{xmessager:this.xmessager,chatDisplay:this.chatDisplay})
		},
		somebodyInHandler({appdata,private_chat_array}){
			this.setPrivateChatArray(private_chat_array)
			MSG_SOMEBODY_IN(appdata,{xmessager:this.xmessager,chatDisplay:this.chatDisplay,roompara:this.roompara})
		},
		somebodyOutHandler({param,appdata,private_chat_array}){
			this.setPrivateChatArray(private_chat_array)
			MSG_SOMEBODY_OUT(param,appdata,{xmessager:this.xmessager,chatDisplay:this.chatDisplay,roompara:this.roompara})
		},
		somebodyChangeLevelHandler({param,private_chat_array}){
			this.setPrivateChatArray(private_chat_array)
		},
		somebodyChangeAppDataHandler({param,private_chat_array}){
			this.setPrivateChatArray(private_chat_array)
		},
		roomHotHandler(param){
			MSG_ROOMHOT(param,this.$store)
		},
		somebodyChatenableHandler(param){
			MSG_SOMEBODY_CHATENABLE(param,{xmessager:this.xmessager,chatDisplay:this.chatDisplay,chat:this.chat})
		},
		kickoutHandler(param){
			MSG_KICKOUT(param,{xmessager:this.xmessager,chatDisplay:this.chatDisplay,chat:this.chat})
		},
		tokenInfoHandler(param){
			MSG_TOKEN_INFO(param,{chat:this.chat,player:this.fullScreenPlayer,xmessager:this.xmessager,store:this.$store,chatDisplay:this.chatDisplay,vm:this})
		},
		tokenQuestHandler(param){
			MSG_TOKEN_REQUEST(param,{chat:this.chat,chatDisplay:this.chatDisplay})
		},
		roomReinitHanlder(param){
			MSG_ROOM_REINIT(param,{store:this.$store,chat:this.chat})
		},
		socketErrorHanlder(){
			MSG_SOCKET_ERROR({chatDisplay:this.chatDisplay,xmessager:this.xmessager})
		},
		socketReconnectHanlder(){
			this.chatDisplay.common_insert('聊天服务器正在重连!', 1);
		},
		commonChatEvents(){
			this.chat.on(this.chat.chatEvents.MSG_LOGIN_ACK,this.loginAckHandler)
			this.chat.on(this.chat.chatEvents.MSG_REENTER,this.reEnterHandler)
			this.chat.on(this.chat.chatEvents.MSG_SESSION_PARAM,this.sessionParamHandler)
			this.chat.on(this.chat.chatEvents.MSG_SOMEBODY_IN,this.somebodyInHandler)
			this.chat.on(this.chat.chatEvents.MSG_SOMEBODY_OUT,this.somebodyOutHandler)
			this.chat.on(this.chat.chatEvents.MSG_SOMEBODY_CHANGELEVEL,this.somebodyChangeLevelHandler)
			this.chat.on(this.chat.chatEvents.MSG_SOMEBODY_CHANGEAPPDATA,this.somebodyChangeAppDataHandler)
			this.chat.on(this.chat.chatEvents.MSG_ROOMHOT,this.roomHotHandler)
			this.chat.on(this.chat.chatEvents.MSG_SOMEBODY_CHATENABLE,this.somebodyChatenableHandler)
			this.chat.on(this.chat.chatEvents.MSG_KICKOUT,this.kickoutHandler)
			this.chat.on(this.chat.chatEvents.MSG_TOKEN_INFO,this.tokenInfoHandler)
			this.chat.on(this.chat.chatEvents.MSG_TOKEN_REQUEST,this.tokenQuestHandler)
			this.chat.on(this.chat.chatEvents.MSG_ROOM_REINIT,this.roomReinitHanlder)
			this.chat.on(this.chat.chatEvents.MSG_SOCKET_ERROR,this.socketErrorHanlder)
			this.chat.on(this.chat.chatEvents.MSG_SOCKET_RECONNECT,this.socketReconnectHanlder)
		},
		offCommonChatEvents(){
			this.chat.off(this.chat.chatEvents.MSG_LOGIN_ACK,this.loginAckHandler)
			this.chat.off(this.chat.chatEvents.MSG_REENTER,this.reEnterHandler)
			this.chat.off(this.chat.chatEvents.MSG_SESSION_PARAM,this.sessionParamHandler)
			this.chat.off(this.chat.chatEvents.MSG_SOMEBODY_IN,this.somebodyInHandler)
			this.chat.off(this.chat.chatEvents.MSG_SOMEBODY_OUT,this.somebodyOutHandler)
			this.chat.off(this.chat.chatEvents.MSG_SOMEBODY_CHANGELEVEL,this.somebodyChangeLevelHandler)
			this.chat.off(this.chat.chatEvents.MSG_SOMEBODY_CHANGEAPPDATA,this.somebodyChangeAppDataHandler)
			this.chat.off(this.chat.chatEvents.MSG_ROOMHOT,this.roomHotHandler)
			this.chat.off(this.chat.chatEvents.MSG_SOMEBODY_CHATENABLE,this.somebodyChatenableHandler)
			this.chat.off(this.chat.chatEvents.MSG_KICKOUT,this.kickoutHandler)
			this.chat.off(this.chat.chatEvents.MSG_TOKEN_INFO,this.tokenInfoHandler)
			this.chat.off(this.chat.chatEvents.MSG_TOKEN_REQUEST,this.tokenQuestHandler)
			this.chat.off(this.chat.chatEvents.MSG_ROOM_REINIT,this.roomReinitHanlder)
			this.chat.off(this.chat.chatEvents.MSG_SOCKET_ERROR,this.socketErrorHanlder)
			this.chat.off(this.chat.chatEvents.MSG_SOCKET_RECONNECT,this.socketReconnectHanlder)
		},
		emojiTan(){
			this.emojiShow = !this.emojiShow
			this.emojiLoad = false
		},
		emojiClose(){
			this.emojiShow = false
			this.emojiLoad = true
		},
		loginOut(){
			this.$store.dispatch('LogOut').then(res=>{
				if(localStorage.getItem("noalertbind_"+this.user.uid)){
					localStorage.removeItem("noalertbind_"+this.user.uid)
				}
				location.reload()
			}).catch(err=>{
				console.log(err)
			})
		}
	},
	mounted(){
		this.height = window.innerHeight
	},
	beforeDestroy(){
		this.$store.commit('SET_PRIVATECHATARRAY',[])
		if(document.querySelector('.layer-loginout-xchat')){
			let parent = getParents(document.querySelector('.layer-loginout-xchat'),'layui-m-layer')
			if(parent){
				parent.parentNode.removeChild(parent)
			}
		}
		if(this.chat){
			if(this.chat.websocket && this.chat.websocket.xchat_protocol.logined){
				this.chat.websocket.logout()
			}
			this.offCommonChatEvents()
		}
		if(this.micLoadingTimer){
			console.log('micLoadingTimer:'+this.micLoadingTimer)
			this.$store.commit('SET_MICLOADING', false)
			this.$store.commit('SET_MICINDEX', 0)
			clearInterval(this.micLoadingTimer)
			this.$store.commit('SET_MICLOADING_TIMER', null)
		}
	}
}
